package com.itheima.controller;


//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.common.Result;
import com.itheima.dto.UserPwdDto;
import com.itheima.entity.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.IUserService;
import com.itheima.util.JwtUtil;
import com.itheima.util.PasswordUtil;
import com.itheima.util.oConvertUtils;
import io.swagger.annotations.ResponseHeader;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.RandomUtil;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author yancy
 * @since 2024-03-07
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private IUserService userService;
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/register")
    public Result<User> register(@Pattern(regexp = "^\\S{5,16}$",message = "需要5-16位字符") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userService.getOne(queryWrapper);
        if (user != null){
            return Result.error("用户名已存在");
        }else {
            //未设置密码，则随机生成一个密码
            if(oConvertUtils.isEmpty(password)){
                password = RandomUtil.randomString(8);
            }
            User user2 = new User();
            user2.setCreateTime(LocalDateTime.now());// 设置创建时间
            user2.setUpdateTime(LocalDateTime.now());
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            user2.setUsername(username);
            user2.setPassword(passwordEncode);
            user2.setSalt(salt);
            userService.save(user2);
            return Result.OK("注册成功");
        }
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String authorization){
        User one = getUser(authorization);
        return Result.ok(one);
    }

    @PostMapping("/update")
    public Result update(@RequestBody @Validated User user){
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return Result.ok("修改成功");
    }

    @PatchMapping("/updateAvatar")
    public Result<User> updateAvatar(@RequestParam @URL String avatar, @RequestHeader(name = "Authorization") String authorization){
        User one = getUser(authorization);
        one.setUserPic(avatar);
        one.setUpdateTime(LocalDateTime.now());
        userService.updateById(one);
        return Result.OK("修改成功",one);
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody UserPwdDto userPwdDto,@RequestHeader(name = "Authorization") String authorization){
        User one = getUser(authorization);
        String oldPwd = userPwdDto.getOldPwd();
        String newPwd = userPwdDto.getNewPwd();
        String confirmPwd = userPwdDto.getConfirmPwd();
        String userPassword = PasswordUtil.encrypt(one.getUsername(), oldPwd, one.getSalt());
        if (!userPassword.equals(one.getPassword())){
            return Result.error("旧密码不正确");
        }
        if (!newPwd.equals(confirmPwd)){
            return Result.error("两次填写的新密码不一致");
        }
        User user = new User();
        BeanUtils.copyProperties(one,user);
        user.setPassword(userPassword);
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(authorization);
        return Result.OK();
    }

    private User getUser(String authorization){
        String username = JwtUtil.getUsername(authorization);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return userService.getOne(queryWrapper);
    }
}

